package com.snb.play.dwebtoon;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.snb.play.dwebtoon.data.DTO_Episode;
import com.snb.play.dwebtoon.data.DTO_EpisodeImage;
import com.snb.play.dwebtoon.data.DTO_EpisodeToon;
import com.snb.play.dwebtoon.util.BinderManager;
import com.snb.play.dwebtoon.util.DBProvider;
import com.snb.play.dwebtoon.util.FileManager;
import com.snb.play.dwebtoon.util.Logger;
import com.snb.play.dwebtoon.util.SharedData;

@SuppressLint("SetJavaScriptEnabled")
public class ToonViewActivity extends BaseActivity implements OnMenuItemClickListener {
	private DTO_EpisodeToon mEpisodeToon;
	public static String TAG = ToonViewActivity.class.getSimpleName();
	private WebView mView;
	// public static String mLastId = "";
	public static final String WebDirectedUrl = "DIRECT_URL";
	private SharedData mSharedData;

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (mView != null)
			mView.saveState(outState);
	}

	boolean isReload = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_item);
		// if (gProgressDialog == null) {
		gProgressDialog = new ProgressDialog(this);
		gProgressDialog.setTitle("데이터 로딩중...");
		// }
		if (savedInstanceState != null) {
			mView.restoreState(savedInstanceState);
			isReload = true;
		}
		if (mSharedData == null)
			mSharedData = (SharedData) getIntent().getSerializableExtra(ContentListActivity.TOONNAME);
		CookieSyncManager.createInstance(this);
		CookieSyncManager.getInstance().startSync();

		CookieManager lkj = CookieManager.getInstance();
		lkj.setAcceptCookie(true);
		CookieSyncManager.getInstance().sync();

		if (mView == null) {
			mView = (WebView) findViewById(R.id.content);
			Button mDown = (Button) findViewById(R.id.tr_btn_down);

			mDown.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					int left = mView.getScrollX();
					mView.scrollTo(left, mView.getScrollY() + mView.getHeight());
				}
			});

			Button mUp = (Button) findViewById(R.id.tr_btn_up);

			mUp.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					int left = mView.getScrollX();
					mView.scrollTo(left, mView.getScrollY() > 0 ? mView.getScrollY() - mView.getHeight() : 0);
				}
			});
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			mView.setWebViewClient(new WebViewClientClass());
			mView.setWebChromeClient(new WebViewChromClientClass());
			mView.getSettings().setAllowFileAccess(true);
			mView.getSettings().setJavaScriptEnabled(true);
			mView.getSettings().setUseWideViewPort(true);
			mView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
			mView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
			mView.setScrollbarFadingEnabled(false);
			mView.setPadding(0, 0, 0, 0);

		}

		if (isReload)
			return;
		boolean lDirect_Url = getIntent().getBooleanExtra(WebDirectedUrl, false);
		Logger.d(TAG, "onResume() == " + lDirect_Url);
		if (!lDirect_Url) {
			mView.getSettings().setBuiltInZoomControls(true);
			mView.loadUrl("http://cartoon.media.daum.net/webtoon/viewer/" + mSharedData.mToonId.trim());
		} else {
			Logger.d("BUM", "aViewId == " + mSharedData.mToonId + " mSharedData.mMainId == " + mSharedData.mMainId + "  mSharedData.mtitle == "
					+ mSharedData.mToonName);
			mEpisodeToon = new DTO_EpisodeToon();
			mEpisodeToon.id = mSharedData.mToonId;

			mEpisodeToon = (DTO_EpisodeToon) DBProvider.getInstance().getObjByID(mEpisodeToon);
			Logger.d(TAG, mEpisodeToon.viewType);
			DTO_EpisodeImage lEpisodeImage = new DTO_EpisodeImage();
			lEpisodeImage.pid = mSharedData.mToonId;
			lEpisodeImage.main_id = mSharedData.mMainId;
			Logger.d(TAG, "DBProvider.getInstance().getAllObjByID(lEpisodeImage)");
			mEpisodeToon.images = DBProvider.getInstance().getAllObjByID(lEpisodeImage);
			setViewByItem();
		}

	}

	public boolean isAdt = false;
	public int AdtCnt = 0;

	private class WebViewClientClass extends WebViewClient {

		@Override
		public void onFormResubmission(WebView view, Message dontResend, Message resend) {
			super.onFormResubmission(view, dontResend, resend);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			// TODO Auto-generated method stub
			if (gProgressDialog != null && gProgressDialog.isShowing())
				gProgressDialog.dismiss();

		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (isAdt && AdtCnt > 1) {
				getRest().setAdultLogin(CookieManager.getInstance().getCookie(view.getUrl()));
				// CookieManager lkj = CookieManager.getInstance();
				// lkj.getCookie(view.getUrl());
			}
			if (url.indexOf("adult") > -1) {
				isAdt = true;
				AdtCnt++;
			}
			if (!isAdt && AdtCnt <= 0)
				if (gProgressDialog != null && !gProgressDialog.isShowing())
					gProgressDialog.show();

			super.onPageStarted(view, url, favicon);
		}

	}

	public void setReadFinish(String aId) {
		DTO_EpisodeToon lToon = new DTO_EpisodeToon();
		DTO_Episode lEp = new DTO_Episode();

		lToon.id = mSharedData.mToonId;
		lToon.isReadFinish = "Y";
		lEp.id = mSharedData.mToonId;
		lEp.isReadFinish = "Y";

		DBProvider.getInstance().updateObjById(lToon);
		DBProvider.getInstance().updateObjById(lEp);
	}

	private class WebViewChromClientClass extends WebChromeClient {

		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			// Logger.d(TAG, message);
			if (message.toString().trim().equalsIgnoreCase("scrollevent")) {
				setReadFinish(mEpisodeToon.id);
				openOptionsMenu();
				result.confirm();
			}

			return true;
		}

		@Override
		public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
			Logger.d(TAG, "consoleMessage == " + consoleMessage.message() + " line == " + consoleMessage.lineNumber() + "  sourceId == "
					+ consoleMessage.sourceId());

			return true;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		mView.stopLoading();
		mView.destroy();
		mView = null;
		CookieSyncManager.getInstance().stopSync();
		super.onDestroy();
	}

	public void setViewByItem() {
		mEpisodeToon.isReadFinish = "N";
		Logger.d(TAG, mEpisodeToon.viewType);
		String lBasePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + BinderManager.PKG_NAME
				+ FileManager.TOONSPATH;
		String lPath = lBasePath + mSharedData.mMainNickName + "/" + mSharedData.mToonId;

		StringBuilder htmlContent = new StringBuilder();
		htmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">");
		htmlContent.append("<meta    name=\"viewport\" content=\"width=device-width, user-scalable=yes\"/>");
		htmlContent.append("<html><title>");
		htmlContent.append(mEpisodeToon.title);
		htmlContent.append("</title>");
		htmlContent.append("<head>");

		// htmlContent.append("<style type=\"text/css\" >");
		// htmlContent.append("#wrapper {margin : 0 auto ;border:1px solid #033;};");
		// htmlContent.append("</style>");
		// htmlContent.append("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\" type=\"text/javascript\"></script>");
		htmlContent.append("<script src=\"file:///android_asset/jquery-1.2.3.pack.js\" type=\"text/javascript\"></script>");
		htmlContent.append("<script src=\"file:///android_asset/jquery.dimensions.pack.js\" type=\"text/javascript\"></script>");
		htmlContent.append("<script type=\"text/javascript\">");
		htmlContent.append("$(document).ready(function(){");
		htmlContent.append("$(window).scroll(function(){");
		htmlContent.append("if  ($(window).scrollTop() >= $(document).height() - $(window).height()){");
		htmlContent.append(" alert(\"scrollevent\");");
		htmlContent.append("}");
		htmlContent.append("});");
		htmlContent.append("});");

		htmlContent.append("</script>");
		htmlContent.append("</head>");
		htmlContent.append("<body id=\"body\">");
		boolean viewtyp = true;
		for (DTO_EpisodeImage item : mEpisodeToon.images) {
			if (item.mediaType.indexOf("image") > -1) {
				if (viewtyp)
					htmlContent.append("<td>");
				htmlContent.append("<img src=\"file://" + lPath + "/" + makeFileName(item.url) + "\"  " + "style=\"width:" + 100
						+ "%;margin: 0px;\" />");
				if (viewtyp)
					htmlContent.append("</td>");
			}
		}

		htmlContent.append("</body></html>");

		lPath = lBasePath + mSharedData.mMainNickName;
		String lFileName = mSharedData.mToonName + ".html";
		try {
			processWebPage(htmlContent.toString(), lPath, lFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		lFileName = null;
		htmlContent = null;
		lPath = null;
		lBasePath = null;
	}

	public void processWebPage(String content, String aPath, String aFileName) throws Exception {
		File path = new File(aPath);
		File file = new File(aPath, aFileName);

		if (!path.exists())
			path.mkdirs();

		OutputStream outStream = new FileOutputStream(file);
		outStream.write(content.getBytes());
		outStream.close();
		outStream = null;

		mView.loadUrl("file:///" + aPath + "/" + aFileName);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main3, menu);
		menu.add(0, 1, 1, "prev").setOnMenuItemClickListener(this);
		menu.add(0, 2, 2, "읽음").setOnMenuItemClickListener(this);
		menu.add(0, 3, 3, "next").setOnMenuItemClickListener(this);

		return true;
	}

	public void goToToon(final boolean wantNext) {
		new Handler().post(new Runnable() {

			@Override
			public void run() {
				setResult(wantNext ? ContentListActivity.FLAG_NEXT : ContentListActivity.FLAG_PREV, null);
				ToonViewActivity.this.finish();
			}
		});
	}

	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
			case 1:
				goToToon(false);
				break;
			case 2:
				setReadFinish(mEpisodeToon.id);
				break;
			case 3:
				goToToon(true);
				break;
		}

		return false;
	}

	@Override
	public void onBackPressed() {
		setResult(ContentListActivity.FLAG_VIEW);
		super.onBackPressed();

	}

	private String makeFileName(String aUrl) {
		String[] returnStrs = aUrl.split("/");
		return returnStrs[returnStrs.length - 1] + ".jpg";
	}

	@Override
	protected void refresh(String aString) {
		Toast.makeText(this, aString + " 다운 완료!", Toast.LENGTH_LONG).show();
	}
}
